import pygame
from plane_sprites import *
class PlaneGame(object):
    """飞机大战主游戏"""

    def __init__(self):
        print("游戏初始化")
    #     创建游戏窗口
        self.screen=pygame.display.set_mode(SCREEN_RECT.size)
    #     创建游戏时钟
        self.clock=pygame.time.Clock()
    #     调用私有方法，精灵和精灵组的创建
        self.__create_sprites()
    #     设置定时器事件-创建敌机  参数1000=1s出现一个
        pygame.time.set_timer(CREAT_ENEMY_EVENT,200)
    #     设置定时器事件-发射子弹  0.5s
        pygame.time.set_timer(HERO_FIRE_EVENT,500)
    def __create_sprites(self):
        # 创建背景精灵和精灵组
        bg1=Background()
        bg2=Background(is_alt=True)
        self.back_ground=pygame.sprite.Group(bg1,bg2)

    #     创建敌机精灵组
        self.enemy_ground=pygame.sprite.Group()
    #     创建英雄
        self.Hero=Hero()
        self.hero_groud=pygame.sprite.Group(self.Hero)
    def start_game(self):
        print("游戏开始……")
        while True:
            # 1.设置刷新频率
            self.clock.tick(FRAME_PER_SEC)
            # 2.事件监听
            self.__event_handler()
            # 3.碰撞检测
            self.__check_collide()
            # 4.更新/绘制精灵组
            self.__update_sprites()
            # 5.更新显示
            pygame.display.update()
            pass
    def __event_handler(self):
        for event in pygame.event.get():
        #     判断是否退出游戏
            if event.type == pygame.QUIT:
                PlaneGame.__game_over()
            elif event.type == CREAT_ENEMY_EVENT:
                enemy = Enemy()
                self.enemy_ground.add(enemy)
            # elif event.type==pygame.KEYDOWN and event.key== pygame.K_RIGHT:
            #     print("向右移动。。。")
            elif event.type == HERO_FIRE_EVENT:
                self.Hero.fire()
        # 使用键盘提供方法获取按键
        keys_pressed = pygame.key.get_pressed()
        self.Hero.speed_x = keys_pressed[pygame.K_RIGHT] * 5 - keys_pressed[pygame.K_LEFT] * 5
        self.Hero.speed_y = keys_pressed[pygame.K_DOWN] * 5 - keys_pressed[pygame.K_UP] * 5
    def __check_collide(self):
    #     1.子弹摧毁敌机
        pygame.sprite.groupcollide(self.Hero.bulltes,self.enemy_ground,True,True)
    #     2.敌机撞毁英雄
        enemies=pygame.sprite.spritecollide(self.Hero,self.enemy_ground,True)
    #     3.判断列表是否有内容
        if len(enemies)>0:
            self.Hero.kill()
            PlaneGame.__game_over()
    def __update_sprites(self):
        self.back_ground.update()
        self.back_ground.draw(self.screen)

        self.enemy_ground.update()
        self.enemy_ground.draw(self.screen)

        self.hero_groud.update()
        self.hero_groud.draw(self.screen)

        self.Hero.bulltes.update()
        self.Hero.bulltes.draw(self.screen)

    @staticmethod
    def __game_over():
        print("游戏结束")
        pygame.quit()
        exit()

if __name__ == '__main__':
    game = PlaneGame()
    game.start_game()
